package com.epfresh.global;

import android.content.Context;
import android.content.res.AssetManager;

import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.bean.Address;
import com.epfresh.bean.CarCntResponse;
import com.epfresh.bean.CartGoods;
import com.epfresh.bean.City;
import com.epfresh.bean.CouponEntity;
import com.epfresh.bean.Market;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wzh on 16-7-12.
 */
public class DataManager {
    public boolean oftenListReFresh;
    public boolean bindStoreReFresh;

    public interface OnCartCountChangeListener {
        public void onCartCountChange(int count);
    }

    //批发市场
    public List<Market> list = new ArrayList<>();
    private static DataManager instance;

    private List<CartGoods> cartGoods = new ArrayList<>();
    private List<Address> addresses = new ArrayList<>();
    private int cartCnt;
    public boolean isNeedRefreshCart;

    public Map<String, List<T>> map = new HashMap<>();

    public Map<String, OnCartCountChangeListener> mapMsgView = new HashMap<>();


    public List<CouponEntity> couponsBest;
    public List<CouponEntity> couponsSelect;
    public List<CouponEntity> coupons;
    public String storePriceStr;

    public static DataManager getInstance() {
        if (instance == null) {
            synchronized (DataManager.class) {
                if (instance == null) {
                    instance = new DataManager();
                }
            }
        }
        return instance;
    }

    public void setCouponsBest(List<CouponEntity> coupons) {
        if (coupons == null) {
            return;
        }
//        if (this.couponsBest ==null){
        this.couponsBest = new ArrayList<>();
//        }
        for (int i = 0; i < coupons.size(); i++) {
            CouponEntity couponEntity = coupons.get(i);
            if (couponEntity != null) {
                CouponEntity clone = couponEntity.clone();
                this.couponsBest.add(clone);
            }
        }
    }

    public void setCouponsSelect(List<CouponEntity> coupons) {
        if (coupons == null) {
            return;
        }
//        if (this.couponsSelect ==null){
        this.couponsSelect = new ArrayList<>();
        for (int i = 0; i < coupons.size(); i++) {
            CouponEntity couponEntity = coupons.get(i);
            if (couponEntity != null) {
                CouponEntity clone = couponEntity.clone();
                    this.couponsSelect.add( clone);
            }
        }
    }

    public void setCoupons(List<CouponEntity> coupons) {
        if (coupons == null) {
            return;
        }
//        if (this.coupons ==null){
        this.coupons = new ArrayList<>();
//        }
        for (int i = 0; i < coupons.size(); i++) {
            CouponEntity couponEntity = coupons.get(i);
            if (couponEntity != null) {
                CouponEntity clone = couponEntity.clone();
                    this.coupons.add(clone);
            }
        }
    }


    public List<CartGoods> getCartGoods() {
        return cartGoods;
    }

    public List<CartGoods> getCloneCartGoods() {
        Gson gson = new Gson();
        String s = gson.toJson(cartGoods);
        return gson.fromJson(s, new TypeToken<List<CartGoods>>() {
        }.getType());
    }

    public void setCartGoods(List<CartGoods> cartGoods) {
        this.cartGoods.clear();
        this.cartGoods.addAll(cartGoods);
    }


    public List<Address> getAddresses() {
        return addresses;
    }

    public void setAddresses(List<Address> addresses) {
        this.addresses = addresses;
    }

    public Map<String, List<T>> getMap() {
        return map;
    }

    public void setMap(Map<String, List<T>> map) {
        this.map = map;
    }

    public int getCartCnt() {
        return cartCnt;
    }

    public void setCartCnt(int cartCnt) {
        this.cartCnt = cartCnt;
    }

    public void setCartCntStatus(int cartCnt) {
        this.cartCnt = cartCnt;
        updateMsgStatus();
    }

    public void clearCart() {
        cartGoods.clear();
        cartCnt = 0;
    }

    OnRequestListener<CarCntResponse> onCntRequestListener = new OnRequestListener<CarCntResponse>() {
        @Override
        public CarCntResponse jsonToObj(String s) {
            return new Gson().fromJson(s, CarCntResponse.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<CarCntResponse> responseEntity, Object o) {


            CarCntResponse responseElement = responseEntity.getResponseElement();

            if (responseElement != null) {
                cartCnt = responseElement.getShoppingCarCnt();
                updateMsgStatus();
//                String shoppingCarCnt = responseElement.get("shoppingCarCnt");
//
//                if (shoppingCarCnt != null && VerificationUtils.isNumeric(shoppingCarCnt)) {
//                    cartCnt = Integer.valueOf(shoppingCarCnt.toString());
//                    updateMsgStatus();
//                }
            }
        }
    };
    OnRequestListener<Map<String, String>> onAddressCntRequestListener = new OnRequestListener<Map<String, String>>() {
        @Override
        public Map<String, String> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<Map<String, String>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<Map<String, String>> responseEntity, Object o) {



        }
    };

    public void updateCartCnt() {
        if (ApplicationHelper.getInstance().getUser().getAccess_token() == null) {
            cartCnt = 0;
            updateMsgStatus();
            return;
        }

        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_cnt);

        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
        re.putParameter("wholeSalesType", "1");
//        RequestEntityMap re = new RequestEntityMap();
//        re.setCmd("appOrder/getShoppingCarCnt");
//
//
//        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
//        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());

        RequestTag tag = new RequestTag();
        tag.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_cnt;

        ApplicationHelper.getInstance().requestSilent(re, tag, onCntRequestListener);

    }
    public void updateAddressCnt(String id) {
        if (ApplicationHelper.getInstance().getUser().getAccess_token() == null) {
            return;
        }
        if (id != null && !"".equals(id)) {

            RequestEntityMap re = new RequestEntityMap();
            re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_account_address_setDefault);
            re.putParameter("id", id);
            re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
            re.putParameter("isDefault", true);
            ApplicationHelper.getInstance().requestSilent(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_account_address_setDefault, onAddressCntRequestListener);
        }
    }

    public void updateMsgStatus() {
        for (String key : mapMsgView.keySet()) {
            OnCartCountChangeListener onCartCountChangeListener = mapMsgView.get(key);
            if (onCartCountChangeListener != null) {
                onCartCountChangeListener.onCartCountChange(cartCnt);
            }

        }
    }

    public void registerMsgView(String key, OnCartCountChangeListener onCartCountChangeListener) {
        mapMsgView.put(key, onCartCountChangeListener);
    }

    public void removeMsgView(String key) {
        mapMsgView.remove(key);
    }

    public City getCityData(Context context) {
        String cityDataStr = "";
        City city = null;
        AssetManager asset = context.getAssets();
        InputStream input = null;
        try {
            input = asset.open("epfresh_area_data");
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(input));
            StringBuilder stringBuilder = new StringBuilder();
            while ((cityDataStr = bufferedReader.readLine()) != null) {
                stringBuilder.append(cityDataStr);
            }
            bufferedReader.close();
            input.close();
            cityDataStr = stringBuilder.toString();//创建超长string
            if (cityDataStr != null && !"".equals(cityDataStr)) {

                JSONObject jsonObject = new JSONObject(cityDataStr);

                String response = jsonObject.getString("response");

                city = new Gson().fromJson(response.trim(), City.class);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return city;
    }



    public HashMap<String,Boolean> collectMap = new HashMap<>();

    public void putCollectMap(String key, boolean value){
        collectMap.put(key,value);
    }
    public void removeCollectMap(String key){
        collectMap.remove(key);
    }

    public Boolean getCollectMap(String key){
        return collectMap.get(key);
    }

    public void clearCollectMap(){
        collectMap.clear();
    }

    public boolean haveToken() {
        return ApplicationHelper.getInstance().getUser().getAccess_token() != null;
    }
}
